﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace FasterWPF
{
    public static class PrintHelper
    {
        public static void PrintFrameworkElement(FrameworkElement visualToPrint, string description)
        {
            PrintDialog pd = new System.Windows.Controls.PrintDialog();

            double originalWidth = visualToPrint.ActualWidth;
            double originalHeight = visualToPrint.ActualHeight;
            double offset=50.0D;

            if (pd.ShowDialog() == true)
            {
                double scale = Math.Min(pd.PrintableAreaWidth/ visualToPrint.ActualWidth, pd.PrintableAreaHeight / visualToPrint.ActualHeight);
                visualToPrint.LayoutTransform = new ScaleTransform(scale, scale);

                visualToPrint.Measure(new Size(pd.PrintableAreaWidth, pd.PrintableAreaHeight));

                //pad by 1/2 inch height and width for printers that require a border. ImageableArea is in 1/96 of an inch
                visualToPrint.Arrange(new Rect(new Point(offset, offset), new Size(pd.PrintableAreaWidth, pd.PrintableAreaHeight)));
                pd.PrintVisual(visualToPrint, description);

                visualToPrint.Measure(new Size(originalWidth, originalHeight));
                visualToPrint.LayoutTransform = new ScaleTransform(1, 1); //scale back to 100% of original width and height
            }
        }
    }
}
